<?php

namespace Lib;

define('LEVEL_FATAL', 0);
define('LEVEL_ERROR', 1);
define('LEVEL_WARN', 2);
define('LEVEL_INFO', 3);
define('LEVEL_DEBUG', 4);

class Logger{
    private $log_file;
    private $level = LEVEL_DEBUG;

    function __construct($name = 'scripts') {
        $dir = dirname(dirname(__FILE__)).'/Logs/'.$name;
        $this->log_file = $dir . '/' . $name . '_' . date('Y-m-d',time()) . ".log";
        if(!is_dir($dir)){
            mkdir($dir, 0777, true);
            $this->clearLog(dirname(dirname(__FILE__)).'/Logs/');
        }
        if(!file_exists($this->log_file)){
            touch($this->log_file);
        }
    }

    protected function clearLog($dir)
    {
        if(Config::$clear_log)
        {
            $files = [];
            $log_num = Config::$max_log_num;
            $ch = opendir($dir);
            if ($ch) {
                while ($filename = readdir($ch)) {
                    if( $filename != '.' && $filename !='..'){
                        array_push($files, $filename);
                    }
                }
                if(count($files) > $log_num){
                    rsort($files);
                    array_splice($files, 0, $log_num);
                    foreach($files as $val){
                        unlink($dir . '/' . $val);
                    }
                }
                closedir ( $ch );
            }
        }
    }
        
    public function set_level($status) {
        $this->level = $status;
    }

    public function debug($tag, $message){
        $this->writeToLog("DEBUG", LEVEL_DEBUG, $tag, $message);
    }

    public function info($tag, $message){
        $this->writeToLog("INFO", LEVEL_INFO, $tag, $message);
    }


    public function warn($tag, $message){
        $this->writeToLog("WARN", LEVEL_WARN, $tag, $message);
    }

    public function error($tag, $message){
        $this->writeToLog("ERROR", LEVEL_ERROR, $tag, $message);
    }

    public function fatal($tag, $message){
        $this->writeToLog("FATAL", LEVEL_FATAL, $tag, $message);
    }

    private function writeToLog($status, $level, $tag, $message) {
        if ($level <= $this->level) {
            $date = date('[Y-m-d H:i:s]');
            $msg = "$date: [$tag][$status] - $message" . PHP_EOL;
            file_put_contents($this->log_file, $msg, FILE_APPEND);
        }
    }
}